<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="modelValue"
    @close="closeForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        编辑
      </div>
    </template>
    <el-scrollbar class="ba-table-form-scrollbar">
      <div
        class="ba-operate-form ba-add-form"
        :style="'width: calc(100% - ' + state.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="onAddSubmit(formRef)"
          :model="state.form"
          label-position="right"
          label-width="200px"
          :rules="rules"
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="state.form!.name" disabled />
          </el-form-item>
          <el-form-item label="班次" prop="className">
            <el-select
              v-model="state.form.className"
              multiple
              placeholder="请选择班次"
              @change="classChange"
            >
              <el-option
                v-for="item in state.classesOptions"
                :key="item.id"
                :label="item.className"
                :value="item.className"
              ></el-option>
            </el-select>
            <div class="block-help" style="width: 100%">
              选择班次前请先选择星期
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div :style="'width: calc(100% - ' + state.labelWidth / 1.8 + 'px)'">
        <el-button @click="closeForm">取消</el-button>
        <el-button
          v-blur
          :loading="state.submitLoading"
          @click="onAddSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, inject } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElNotification } from "element-plus"; //处理导航信息
import { Delete } from "@element-plus/icons-vue";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useDeviceWarnSet } from "@/store/backend/DeviceM/warnSet";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useLongRange } from "@/store/backend/DeviceM/longRange";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import baTable from "@/utils/baTable";

const access = useAccess();
const equipClass = inject("equipClass") as any;
const schedule = inject("schedule") as any;
const { proxy } = useCurrentInstance(); //mitt
const LR = useLongRange();
const carbon = useCarbon();
interface Props {
  modelValue: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
});

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();

const closeForm = () => {
  emits("update:modelValue", false);
};

const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "日历记录名称不能为空", trigger: "blur" }],
  className: [{ required: true, message: "班次不能为空", trigger: "blur" }],
});

const state: {
  labelWidth: number;
  submitLoading: boolean;
  form: anyObj;
  className: any[];
  checkWeeks: any[];
  weeksOptions: anyObj[];
  classesOptions: anyObj[];
} = reactive({
  labelWidth: 160,
  submitLoading: false,
  form: {
    ancestors: "", //祖级id
    className: [], //班次
    createBy: "",
    createTime: "",
    date: "2023-11-01",
    dayOfWeek: "星期三",
    deptId: 103,
    equipmentCode: "DZ-SCSB-AII-034",
    id: 26,
    name: null,
    priority: null,
    remark: null,
    updateBy: null,
    updateTime: null,
  },
  classesOptions: [], //班次列表
  weeksOptions: [
    {
      value: "monday",
      label: "周一",
    },
    {
      value: "tuesday",
      label: "周二",
    },
    {
      value: "wednesday",
      label: "周三",
    },
    {
      value: "thursday",
      label: "周四",
    },
    {
      value: "friday",
      label: "周五",
    },
    {
      value: "saturday",
      label: "周六",
    },
    {
      value: "sunday",
      label: "周七",
    },
  ],
  checkWeeks: [], //被选择的星期
  className: [],
});

const onAddSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      schedule
        .editScheduleRecord(state.form)
        .then((res: any) => {
          //关闭表单
          closeForm();
          //刷新工厂日历记录列表
          proxy.eventBus.emit("getScheduleOfFactory", schedule.backupSearch);
        })
        .catch((err: any) => {
          console.log("修改失败", err);
          ElNotification({
            type: "warning",
            message: err.msg,
          });
        });
    } else {
      ElNotification({
        type: "warning",
        message: "修改失败，请查看是否遗漏",
      });
    }
  });
};

//星期选择
const weekChange = (val: any) => {
  console.log("星期选择", val, state.checkWeeks);
};
//班次选择
const classChange = (val: any) => {
  console.log("星期选择", val, state.checkWeeks);
};

proxy.eventBus.on("everyWorkDay", (data: any) => {
  console.log("workDay工厂日历记录", data);
  state.form = data;
  console.log("state.form", state.form);
});

// 获取活性炭最新设定数据
// const getNewActiveCarbon = (filter: any) => {
//   carbon.getCarbonItemById(filter).then((res: any) => {
//     console.log("指令通过id获取数据", res);
//     state.form.lifeValue = res.rows[0].lifeValue;
//   });
// };

onMounted(() => {
  //获取设备班次
  equipClass
    .getStationByRole({ pageSize: 1000 })
    .then((res: any) => {
      state.classesOptions = res.rows;
    })
    .catch((err: any) => {});
});
onBeforeUnmount(() => {
  proxy.eventBus.off("order");
  proxy.eventBus.off("everyWorkDay");
});
</script>

<style scoped lang="scss">
.add-item-content {
  display: none;
}
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
</style>
